package ReadJmeterLog;

import ReadJmeterLog.bean.Nmon;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.text.DecimalFormat;
import java.util.Map;

public class CreatePerformanceTestExcel {

    public static void main(String[] args) {


        //1
        ReadNmon readNmon = new ReadNmon();

        Map<String,Nmon> nmonMap = readNmon.readNmonInfo(new File("D://jmeter.log"));



        //2
        CreatePerformanceTestExcel createPerformanceTestExcel = new CreatePerformanceTestExcel();
        Workbook workbook = new XSSFWorkbook();
        Sheet singleSheet = workbook.createSheet("单场景");


        workbook = createPerformanceTestExcel.generateServerPerformanceInformation(workbook, singleSheet, 1, 1, nmonMap);
        createPerformanceTestExcel.writeExcel(workbook);
    }


    /**
     * 将nmon监控的服务器性能信息生成Excel
     * @param nmonMap
     */
    public Workbook generateServerPerformanceInformation(Workbook workbook, Sheet sheet, int rowNum, int cellNum,Map<String, Nmon> nmonMap){

        int infoNum = 4;
        Row ipRow = sheet.createRow(rowNum + 0);//IP行
        Row fieldRow = sheet.createRow(rowNum + 1);//字段行
        Row dataRow = sheet.createRow(rowNum + 2);//数据行
        CellStyle cellStyle;
        XSSFCellStyle xssfCellStyle;
        int heightNum = 0;
        StringBuilder stringBuilder;//保存Net信息
        String ip;
        Font font;
        DecimalFormat decimalFormat = new DecimalFormat("0.00");

        for(Map.Entry<String,Nmon> nmonEntry : nmonMap.entrySet()){
            ip = nmonEntry.getKey();
            Nmon nmon = nmonEntry.getValue();
            Cell cell;

            //----------------
            //ipRow
            //----------------

            //设置样式
            xssfCellStyle = (XSSFCellStyle) workbook.createCellStyle();
            //设置样式-对齐方式
            xssfCellStyle.setAlignment(HorizontalAlignment.CENTER);//水平对齐
            xssfCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐
            //设置样式-背景颜色
            xssfCellStyle.setFillForegroundColor(new XSSFColor( new java.awt.Color(221, 217, 196), new DefaultIndexedColorMap()));
            xssfCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);


            ////设置样式-宋体、9号字、粗体字
            font = workbook.createFont();
            font = setFont(font,"宋体",9, true);
            xssfCellStyle.setFont(font);



            //合并单元格
            CellRangeAddress cellAddresses = new CellRangeAddress(
                    rowNum,
                    rowNum,
                    cellNum,
                    cellNum + 3
            );
            sheet.addMergedRegion(cellAddresses);

            //为合并单元格设置边框
            setBorder(cellAddresses, ipRow, xssfCellStyle, BorderStyle.THIN, IndexedColors.BLACK.getIndex());

            //1.创建列；2.设置值；3.设置样式
            cell = ipRow.createCell(cellNum);
            cell.setCellValue(ip);
            cell.setCellStyle(xssfCellStyle);



            //----------------
            //fieldRow
            //----------------

            //设置样式
            xssfCellStyle = (XSSFCellStyle) workbook.createCellStyle();
            //设置样式-对齐方式
            xssfCellStyle.setAlignment(HorizontalAlignment.CENTER);//水平对齐
            xssfCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐
            //设置样式-背景颜色
            xssfCellStyle.setFillForegroundColor(new XSSFColor( new java.awt.Color(221, 217, 196), new DefaultIndexedColorMap()));
            xssfCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            //设置样式-边框
            setBorder(xssfCellStyle, BorderStyle.THIN, IndexedColors.BLACK.getIndex());


            //设置样式-宋体、9号字、粗体字
            font = workbook.createFont();
            font = setFont(font,"宋体",9, true);
            xssfCellStyle.setFont(font);

            //CPU
            //1.创建行；2.设置值；3.设置样式
            cell = fieldRow.createCell(cellNum + 0);
            cell.setCellValue("CPU%");
            cell.setCellStyle(xssfCellStyle);

            //MEN
            //1.创建行；2.设置值；3.设置样式
            cell = fieldRow.createCell(cellNum + 1);
            cell.setCellValue("MEN%");
            cell.setCellStyle(xssfCellStyle);

            //NET
            //1.创建行；2.设置值；3.设置样式
            cell = fieldRow.createCell(cellNum + 2);
            cell.setCellValue("Net");
            cell.setCellStyle(xssfCellStyle);

            //I/O
            //1.创建行；2.设置值；3.设置样式
            cell = fieldRow.createCell(cellNum + 3);
            cell.setCellValue("I/O%");
            cell.setCellStyle(xssfCellStyle);

            //----------------
            //dataRow - CPU
            //----------------

            //设置样式
            cellStyle = workbook.createCellStyle();
            //设置样式-对齐方式
            cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平对齐
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐
            //设置样式-边框
            setBorder(cellStyle, BorderStyle.THIN, IndexedColors.BLACK.getIndex());

            //设置样式-宋体、9号字
            font = workbook.createFont();
            font = setFont(font,"宋体",9, false);
            cellStyle.setFont(font);

            //1.创建行；2.设置值；3.设置样式
            cell = dataRow.createCell(cellNum + 0);
            cell.setCellValue(decimalFormat.format(Double.valueOf(nmon.getCPUSys())) + "%");
            cell.setCellStyle(cellStyle);

            //列宽自适应（参数为列索引，从0开始）
            sheet.autoSizeColumn(cellNum + 0);

            //----------------
            //dataRow - MEN
            //----------------

            //1.创建行；2.设置值；3.设置样式
            cell = dataRow.createCell(cellNum + 1);
            cell.setCellValue(decimalFormat.format(Double.valueOf(nmon.getTotalMenUse())) + "%");
            cell.setCellStyle(cellStyle);

            //列宽自适应（参数为列索引，从0开始）
            sheet.autoSizeColumn(cellNum + 1);

            //----------------
            //dataRow - Net
            //----------------

            //设置样式-显示换行
            cellStyle.setWrapText(true);

            //数据处理
            stringBuilder = new StringBuilder();
            if(nmon.getEth0_write_KB_s() != null && nmon.getEth0_write_KB_s().length() > 0){
                stringBuilder.append("eth0-write-KB/s=" + nmon.getEth0_write_KB_s() + "\n");
                heightNum++;
            }
            if(nmon.getLo_write_KB_s() != null && nmon.getLo_write_KB_s().length() > 0){
                stringBuilder.append("lo-write-KB/s=" + nmon.getLo_write_KB_s() + "\n");
                heightNum++;
            }
            if(nmon.getEth0_read_KB_s() != null && nmon.getEth0_read_KB_s().length() > 0){
                stringBuilder.append("eth0-read-KB/s=" + nmon.getEth0_read_KB_s());
                heightNum++;
            }

            //1.创建行；2.设置值；3.设置样式
            cell = dataRow.createCell(cellNum + 2);
            cell.setCellValue(stringBuilder.toString());
            cell.setCellStyle(cellStyle);

            //列宽自适应（参数为列索引，从0开始）
            sheet.autoSizeColumn(cellNum + 2);

            //----------------
            //dataRow - I/O
            //----------------

            //设置样式-显示换行
            cellStyle.setWrapText(true);

            //数据处理
            stringBuilder = new StringBuilder();
            if(nmon.getTotalDiskRead() != null && nmon.getTotalDiskRead().length() > 0){
                stringBuilder.append("TotalDiskRead=" + nmon.getTotalDiskRead() + "KB/s\n");
            }
            if(nmon.getTotalDiskWrite() != null && nmon.getTotalDiskWrite().length() > 0){
                stringBuilder.append("TotalDiskWrite=" + nmon.getTotalDiskWrite() + "KB/s\n");
            }
            if(nmon.getTotalDiskIO() != null && nmon.getTotalDiskIO().length() > 0){
                stringBuilder.append("TotalDiskIO=" + nmon.getTotalDiskIO() + "KB/s");
            }

            //1.创建行；2.设置值；3.设置样式
            cell = dataRow.createCell(cellNum + 3);
            cell.setCellValue(stringBuilder.toString());
            cell.setCellStyle(cellStyle);

            //列宽自适应（参数为列索引，从0开始）
            sheet.autoSizeColumn(cellNum + 3);



            //每4个数据一组（CPU、MEM、NET、IO）
            cellNum = cellNum + infoNum;

            //变为heightNum倍行高
            dataRow.setHeightInPoints((heightNum * sheet.getDefaultRowHeightInPoints()));
            heightNum = 0;
        }

        return workbook;
    }

    //TODO 生成单交易场景
    public void createSingleScene(){


    }

    //TODO 生成混合交易场景

    //TODO 生成稳定性交易场景


    /**
     * 写入Excel
     * @param workbook
     * @Auther jiangboyang 20210501
     * TODO 指定写入文件名及目录 20210506
     */
    public void writeExcel(Workbook workbook){
        try(OutputStream outputStream = new FileOutputStream("D://workbook.xlsx")){
            workbook.write(outputStream);
        } catch (FileNotFoundException e) {
            System.out.println("文件没有找到");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("我也不知道哪里错了");
            e.printStackTrace();
        }
        finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置字体、字号、是否粗体
     * @param font
     * @param fontName
     * @param FontHeightInPoints
     * @param isBold
     * @return
     * @Auther jiangboyang 20210507
     */
    public Font setFont(Font font, String fontName, int FontHeightInPoints, boolean isBold){
        font.setFontName(fontName);
        font.setFontHeightInPoints((short)FontHeightInPoints);
        font.setBold(isBold);
        return font;
    }

    /**
     * 为单元格设置边框（一个单元格）
     * @param xssfCellStyle
     * @param borderStyle
     * @param color
     * @Auther jiangboyang 20210507
     */
    public void setBorder(XSSFCellStyle xssfCellStyle, BorderStyle borderStyle, short color){

        xssfCellStyle.setBorderTop(borderStyle);//顶部
        xssfCellStyle.setTopBorderColor(color);

        xssfCellStyle.setBorderBottom(borderStyle);//底部
        xssfCellStyle.setBottomBorderColor(color);

        xssfCellStyle.setBorderLeft(borderStyle);//左侧
        xssfCellStyle.setLeftBorderColor(color);

        xssfCellStyle.setBorderRight(borderStyle);//右侧
        xssfCellStyle.setRightBorderColor(color);
    }

    public void setBorder(CellStyle cellStyle, BorderStyle borderStyle, short color){

        cellStyle.setBorderTop(borderStyle);//顶部
        cellStyle.setTopBorderColor(color);

        cellStyle.setBorderBottom(borderStyle);//底部
        cellStyle.setBottomBorderColor(color);

        cellStyle.setBorderLeft(borderStyle);//左侧
        cellStyle.setLeftBorderColor(color);

        cellStyle.setBorderRight(borderStyle);//右侧
        cellStyle.setRightBorderColor(color);
    }

    /**
     * 为单元格设置边框（一个或多个单元格）
     * @param cellRangeAddress
     * @param row
     * @param borderStyle
     * @param color
     * @Authter jiangboyang 20210507
     */
    public void setBorder(CellRangeAddress cellRangeAddress, Row row, XSSFCellStyle xssfCellStyle, BorderStyle borderStyle, short color){

        int firstRowNum;//首行
        int lastRowNum;//最后一行
        int firstColumn;//首列
        int lastColumn;//最后一列
        Cell cell;

        firstRowNum = cellRangeAddress.getFirstRow();
        lastRowNum = cellRangeAddress.getLastRow();
        firstColumn = cellRangeAddress.getFirstColumn();
        lastColumn = cellRangeAddress.getLastColumn();

        //第1行
        //遍历每1列

        //第2~倒数第2行
        //遍历每1列

        //第3行
        //遍历每1列

        for(int i = firstRowNum; i <= lastRowNum; i++){

            //合并单元格为1行
            if(firstRowNum == lastRowNum){
                //1列
                if(firstColumn == lastColumn){
                    cell = row.createCell(firstColumn);
                    xssfCellStyle.setBorderLeft(borderStyle);//左侧
                    xssfCellStyle.setLeftBorderColor(color);
                    xssfCellStyle.setBorderRight(borderStyle);//右侧
                    xssfCellStyle.setRightBorderColor(color);
                    xssfCellStyle.setBorderTop(borderStyle);//顶部
                    xssfCellStyle.setTopBorderColor(color);
                    xssfCellStyle.setBorderBottom(borderStyle);//底部
                    xssfCellStyle.setBottomBorderColor(color);
                    cell.setCellStyle(xssfCellStyle);
                }
                //2列
//                else if((lastColumn - firstColumn) == 1){
//
//                }
                //2~N列
                else if((lastColumn - firstColumn) >= 1){
                    for(int j = firstColumn; j <= lastColumn; j++){

                        cell = row.createCell(j);
                        if(j == firstColumn){
                            xssfCellStyle.setBorderLeft(borderStyle);//左侧
                            xssfCellStyle.setLeftBorderColor(color);

                        }
                        else if(j == lastColumn){
                            xssfCellStyle.setBorderRight(borderStyle);//右侧
                            xssfCellStyle.setRightBorderColor(color);
                        }

                        xssfCellStyle.setBorderTop(borderStyle);//顶部
                        xssfCellStyle.setTopBorderColor(color);
                        xssfCellStyle.setBorderBottom(borderStyle);//底部
                        xssfCellStyle.setBottomBorderColor(color);
                        cell.setCellStyle(xssfCellStyle);
                    }
                }
            }
            //合并单元格为2行
            else if((lastRowNum - firstRowNum) == 1){

            }
            //合并单元格为多行
            else{

            }
        }




//        cell = row.createCell(cellNum + 1);
//        xssfCellStyle.setBorderBottom(BorderStyle.THIN);
//        xssfCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
//
//        xssfCellStyle.setBorderLeft(BorderStyle.THIN);
//        xssfCellStyle.setRightBorderColor(IndexedColors.RED.getIndex());
//
//        xssfCellStyle.setBorderTop(BorderStyle.THIN);
//        xssfCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
//        cell.setCellStyle(xssfCellStyle);
//
//        cell = row.createCell(cellNum + 1);
//        xssfCellStyle.setBorderTop(BorderStyle.THIN);
//        xssfCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
//        cell.setCellStyle(xssfCellStyle);
//
//        cell = row.createCell(cellNum + 2);
//        xssfCellStyle.setBorderTop(BorderStyle.THIN);
//        xssfCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
//        cell.setCellStyle(xssfCellStyle);
//
//        cell = row.createCell(cellNum + 3);
//        xssfCellStyle.setBorderTop(BorderStyle.THIN);
//        xssfCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
//
//        xssfCellStyle.setBorderRight(BorderStyle.THIN);
//        xssfCellStyle.setRightBorderColor(IndexedColors.BLUE.getIndex());
//
//        xssfCellStyle.setBorderBottom(BorderStyle.THIN);
//        xssfCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
//        cell.setCellStyle(xssfCellStyle);
    }


}
